package edu.nyu.hps.architecture;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * This class is a dedicated thread for each client on the server
 * 
 * @author hiralrajani
 * 
 */
public class ClientThread extends Thread {

	private Socket socket = null;
	Player player, opponent;

	public ClientThread(Socket s, Player p, Player o) {
		super("Client");
		this.socket = s;
		this.player = p;
		this.opponent = o;
	}

	/**
	 * Starts a dedicated thread for each client
	 */
	public void run() {
		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));

			String inputLine, outputLine = null;
			Protocol myProtocol = new Protocol(player, opponent);

			// Keep listening to the client
			while (true) {
				double time = System.currentTimeMillis();
				double processTime = 0;
				while ((inputLine = in.readLine()) == null) {
					processTime = System.currentTimeMillis() - time;
					if (processTime / 1000 > player.time) {
						break;
					}
				}
				// Keeping track of time for the client
				processTime = System.currentTimeMillis() - time;
				player.time -= (int) (processTime / 1000);

				if (inputLine == null || player.time <= 0) {
					out.println("NACK:Too Slow");
					System.out.println(player.name + " is slow");
					break;
				}

//				System.out.println(player.who + " to server: " + inputLine);
				outputLine = myProtocol.processInput(inputLine);
//				 System.out.println("Server to " + player.who + ":" +
//				 outputLine);
				// Writing messages to the client
				out.println(outputLine);
				if (outputLine.charAt(0) == 'S') {
					System.out.println("Server to " + player.who + ":"
							+ outputLine);
					break;
				}
			}

			// Closing all the handles
			out.close();
			in.close();
			socket.close();

		} catch (IOException e) {
			System.out.println("No I/O");
		}

	}
}
